/*
 * 官网地站:http://www.mob.com
 * 技术支持QQ: 4006852216
 * 官方微信:ShareSDK   （如果发布新版本的话，我们将会第一时间通过微信将版本更新内容推送给您。如果使用过程中有任何问题，也可以通过微信与我们取得联系，我们将会在24小时内给予回复）
 *
 * Copyright (c) 2013年 mob.com. All rights reserved.
 */

package com.wbdgj.wxapi;


import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.Message;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.widget.Toast;

import com.google.gson.Gson;
import com.google.gson.JsonObject;
import com.google.gson.internal.LinkedTreeMap;
import com.igexin.sdk.PushManager;
import com.tencent.mm.opensdk.constants.ConstantsAPI;
import com.tencent.mm.opensdk.modelbase.BaseReq;
import com.tencent.mm.opensdk.modelbase.BaseResp;
import com.tencent.mm.opensdk.modelmsg.SendAuth;
import com.tencent.mm.opensdk.openapi.IWXAPI;
import com.tencent.mm.opensdk.openapi.IWXAPIEventHandler;
import com.tencent.mm.opensdk.openapi.WXAPIFactory;
import com.wbdgj.base.BaseApplication;
import com.wbdgj.http.HttpAdapter;
import com.wbdgj.http.OnNoResponseListener;
import com.wbdgj.http.OnResponseListener;
import com.wbdgj.model.ResultObjectModel;
import com.wbdgj.ui.MainActivity;
import com.wbdgj.ui.login.LoginActivity;
import com.wbdgj.ui.mine.InformaticaNewActivity;
import com.wbdgj.ui.mine.WxPhoneActivity;
import com.wbdgj.utils.SpKeyUtils;
import com.wbdgj.utils.ToastUtils;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;

import cn.jiguang.share.wechat.WeChatHandleActivity;
import retrofit2.Call;

/** 微信客户端回调activity示例 */
public class WXEntryActivity extends WeChatHandleActivity implements IWXAPIEventHandler {

    private static final String TAG = "WXEntryActivity";
    private Context context = this;
    private String wechatAppID = "wxf1069c4f961f956e";
    private String wechatAppSecret = "2c0c2f2e507f3b84ef5b33dcd1fb6dd2";
    private String cid;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        cid = PushManager.getInstance().getClientid(this);
        IWXAPI api = WXAPIFactory.createWXAPI(this, wechatAppID, true);
        api.handleIntent(getIntent(), this);
    }

    @Override
    public void onReq(BaseReq req) {
        Log.i(TAG, "onReq...");
    }

    @Override
    public void onResp(BaseResp resp) {
        Log.i(TAG, "onResp: " + resp);
        String code = null;
        switch (resp.errCode) {
            case BaseResp.ErrCode.ERR_OK:// 用户同意,只有这种情况的时候code是有效的
                if(resp.getType()== ConstantsAPI.COMMAND_SENDAUTH){
                    code = ((SendAuth.Resp) resp).code;
                    Log.i("zp", code);
                    try {
                        requesUserInfo(code);
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }else if(resp.getType()==ConstantsAPI.COMMAND_SENDMESSAGE_TO_WX){
                    Toast.makeText(WXEntryActivity.this, "分享成功", Toast.LENGTH_SHORT).show();
                    finish();
                }

                break;
            case BaseResp.ErrCode.ERR_AUTH_DENIED:// 用户拒绝授权
                Log.i("zp", "用户拒绝授权");
                break;
            case BaseResp.ErrCode.ERR_USER_CANCEL:// 用户取消
                Log.i("zp", "用户取消");
                break;

            default:// 发送返回

                break;
        }
        finish();
    }

    public void requesUserInfo(final String code) {
        final String path = "https://api.weixin.qq.com/sns/oauth2/access_token?appid=" + wechatAppID
                + "&secret=" + wechatAppSecret + "&code=" + code
                + "&grant_type=authorization_code";
        final android.os.Handler handler = new android.os.Handler() {
            public void handleMessage(Message msg) {
                super.handleMessage(msg);
                Bundle b = msg.getData();
                String newsTemp = b.getString("msg");
                Log.e("zp","微信登录成功-----" + newsTemp );
                Log.e("zp","微信登录成功111-----" + b.getString("state") );

                Gson gson = new Gson();
                JsonObject jsonObject  = gson.fromJson(newsTemp, JsonObject.class);
                Log.e("zp", String.valueOf(jsonObject.get("openid")).replace("\"", ""));
                if (BaseApplication.getInstance().getSpUtil().getString(SpKeyUtils.WXFROM).equals("1")){
                    wexin( String.valueOf(jsonObject.get("openid")).replace("\"", ""),  String.valueOf(jsonObject.get("unionid")).replace("\"", ""));
                }else if (BaseApplication.getInstance().getSpUtil().getString(SpKeyUtils.WXFROM).equals("2")){
                    bindwx( String.valueOf(jsonObject.get("openid")).replace("\"", ""),  String.valueOf(jsonObject.get("unionid")).replace("\"", ""));
                }

            }
        };

        new Thread(new Runnable() {
            @Override
            public void run() {
                BufferedReader br = null;
                try {
                    URL url = new URL(path);
                    HttpURLConnection httpconn = (HttpURLConnection) url.openConnection();
                    httpconn.setRequestProperty("accept", "*/*");
                    httpconn.setDoInput(true);
                    httpconn.setDoOutput(true);
                    httpconn.setConnectTimeout(5000);
                    httpconn.connect();
                    int stat = 200;
                    String msg = "";
                    if (stat == 200) {
                        br = new BufferedReader(new InputStreamReader(httpconn.getInputStream()));
                        msg = br.readLine();
                        Bundle b = new Bundle();
                        b.putString("msg", msg);
                        Message m = new Message();
                        m.setData(b);
                        handler.sendMessage(m);
                    } else {
                        msg = "请求失败";
                        Log.i(TAG, msg);
                    }
                } catch (MalformedURLException e) {
                    e.printStackTrace();
                } catch (IOException e) {
                    e.printStackTrace();
                } finally {
                    if (br != null) {
                        try {
                            br.close();
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                    }
                }
            }
        }).start();
    }


    private void wexin(final String opid, final String UNIONID) {
        Call<ResultObjectModel> call = HttpAdapter.getSerives().wexin(opid, UNIONID);
        call.enqueue(new OnNoResponseListener<ResultObjectModel>(context) {
            @Override
            protected void onSuccess(ResultObjectModel userModelBaseResultModel) {
                if(userModelBaseResultModel.getResultCode().equals("0000")){
                    ToastUtils.toastShort(userModelBaseResultModel.getResultMsg());
                    LinkedTreeMap linkedTreeMap = (LinkedTreeMap) userModelBaseResultModel.getData();
                    PushManager.getInstance().bindAlias(context, linkedTreeMap.get("PHONE")+"", cid);

                    BaseApplication.getInstance().getSpUtil().putString(SpKeyUtils.TOKEN, linkedTreeMap.get("TOKEN")+"");
                    BaseApplication.getInstance().getSpUtil().putString(SpKeyUtils.IS_AUTO_LOGIN, "1");
                    if (linkedTreeMap.containsKey("NAME")){
                        if ((linkedTreeMap.get("NAME")+"").equals("")){
                            Intent intent = new Intent(context, MainActivity.class);
                            intent.putExtra("sm", 1);
                            intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK | Intent.FLAG_ACTIVITY_NEW_TASK);
                            startActivity(intent);
                        }else{
                            Intent intent = new Intent(context, MainActivity.class);
                            intent.putExtra("sm", 0);
                            intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK | Intent.FLAG_ACTIVITY_NEW_TASK);
                            startActivity(intent);
                        }
                    }else{
                        Intent intent = new Intent(context, MainActivity.class);
                        intent.putExtra("sm", 1);
                        intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK | Intent.FLAG_ACTIVITY_NEW_TASK);
                        startActivity(intent);
                    }
                }else if(userModelBaseResultModel.getResultCode().equals("7777")){
                    startActivity(new Intent(context, WxPhoneActivity.class).putExtra("openId", opid).putExtra("UNIONID", UNIONID));
                }
            }
        });
    }

    private void bindwx(final String opid, String unionid) {
        Call<ResultObjectModel> call = HttpAdapter.getSerives().bindwx(opid, unionid, BaseApplication.getInstance().getSpUtil().getString(SpKeyUtils.TOKEN));
        call.enqueue(new OnNoResponseListener<ResultObjectModel>(context) {
            @Override
            protected void onSuccess(ResultObjectModel userModelBaseResultModel) {
                if(userModelBaseResultModel.getResultCode().equals("0000")){
                    ToastUtils.toastShort("绑定成功");
                    InformaticaNewActivity.find();
                }else if (userModelBaseResultModel.getResultCode().equals("1111")){
                    ToastUtils.toastShort("账号没有登录或在其它地方登录");
                    BaseApplication.getInstance().getSpUtil().putString(SpKeyUtils.TOKEN, "");
                    BaseApplication.getInstance().getSpUtil().putString(SpKeyUtils.IS_AUTO_LOGIN, "2");
                    PushManager.getInstance().unBindAlias(context, BaseApplication.getInstance().getSpUtil().getString(SpKeyUtils.LOGIN_PHONE), false, BaseApplication.getInstance().getSpUtil().getString(SpKeyUtils.CID));
                    Intent intent = new Intent(context, LoginActivity.class);
                    intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK | Intent.FLAG_ACTIVITY_NEW_TASK);
                    startActivity(intent);
                }else{
                    ToastUtils.toastShort(userModelBaseResultModel.getResultMsg());
                }
            }
        });
    }
}